package com.goalias.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.goalias.constant.RedisConstants;
import com.goalias.feign.domain.UserInfo;
import com.goalias.domain.dto.LoginDto;
import com.goalias.domain.entity.User;
import com.goalias.domain.vo.LoginVo;
import com.goalias.mapper.UserMapper;
import com.goalias.properties.JwtProperties;
import com.goalias.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goalias.service.RedisService;
import com.goalias.util.JWTUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author goalias
 * @since 2024-12-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private RedisService redisService;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String username = loginDto.getUserName();
        String originPassword = loginDto.getPassword();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String password = DigestUtil.sha256Hex(originPassword+jwtProperties.getSalt(), "UTF-8");
        queryWrapper.eq("user_name", username);
        queryWrapper.eq("password",password);
        queryWrapper.eq("status", "0");
        queryWrapper.eq("del_flag", "0");
        User user = getOne(queryWrapper);
        if (null == user) {
            return null;
        }
        user.setLastTime(LocalDateTime.now());
        user.setIp(loginDto.getIp());
        user.setAddress(loginDto.getAddress());
        syncLogin(user);
        // 生成token
        String token = JWTUtil.createJWT(jwtProperties.getJwtSecret(), Long.parseLong(jwtProperties.getJwtTtl()),  new HashMap<>(){
            {
                put("userId", user.getId().toString());
            }
        });
        return new LoginVo(user.getId(), user.getUserName(), token);
    }

    public void syncLogin(User user) {
        updateById(user);
        UserInfo.set(new UserInfo(user.getId(), user.getNickName(), user.getPhone(), user.getEmail(),
                user.getIp(), user.getAddress(),LocalDateTime.now()));
        redisService.set(RedisConstants.USERINFO+user.getId(), JSONUtil.toJsonStr(UserInfo.get()), Long.parseLong(jwtProperties.getJwtTtl()));
    }

    @Override
    public boolean register(User user) {
        user.setPassword(DigestUtil.sha256Hex(user.getPassword()+jwtProperties.getSalt(), "UTF-8"));
        return save(user);

    }

    @Override
    public void logout(Long userId, String tokenHeader) {
        redisService.set(RedisConstants.USER_TOKEN+userId, tokenHeader);
    }

    @Override
    public boolean updateInfo(User user) {
        return updateById(user);
    }


}
